//
//  ST_DaliyMomentDetailController.swift
//  btvideo
//
//  Created by mac on 2020/7/23.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import SwiftyUserDefaults
import MJRefresh

class ST_DaliyMomentDetailController: ST_BTLightBarViewController {
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        self.header.continuePlay()
        print("将要重新 播放")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        self.header.pause_video()
        print("将要暂停")
        
        
    }
    
    var openInputCommentBar = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("日常")
        
        
        self.right_nav_btn.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_更多操作")!)
        
        self.right_nav_btn.isHidden = false
        
        
        let moreButtonW = 17.cgFloat
        
        right_nav_btn.snp.remakeConstraints { (make) in
            make.centerY.equalTo(title_nav_btn)
            make.right.equalToSuperview().offset(-15+(44-moreButtonW)/2.0)
            make.width.height.equalTo(44)
        }
        
         
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+44, left: 0, bottom: 0, right: 0))
        }
        
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
        self.header.reload_cell_closure = {[weak self] in
            
            if let strongSelf = self , let hModel = strongSelf.headerModel{
                
                strongSelf.header.model = hModel
                
                strongSelf.header.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: hModel.cellHeight)
                
                strongSelf.tableView.tableHeaderView = strongSelf.header
                
            }
            
        }
        
        
        view.addSubview(bottom_input_action_view)
        bottom_input_action_view.snp.makeConstraints { (make) in
            make.height.equalTo(ST_PecGroupBottomView.height)
            make.bottom.left.right.equalToSuperview()
        }
        
        view.addSubview(comment_input_mask_view)
        comment_input_mask_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(comment_input_bar)
        comment_input_bar.snp.makeConstraints { (make) in
            make.height.equalTo(ST_CommentInputBar.height)
            make.bottom.left.right.equalToSuperview()
        }
        
        
        
        
        
        request_data()
        
        NotificationCenter.default.addObserver(self, selector: #selector(goback_topmost_controller_handle(noti:)), name: Notification.Name.goback_topmost_controller, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(present_to_controller_handle(noti:)), name: Notification.Name.global_present_controller, object: nil)
    }
    
    deinit {
        print("一定要 释放哦")
    }

//    MARK: - Notification Observer
    @objc fileprivate func present_to_controller_handle(noti:Notification){
        
        self.header.pause_video()
        
    }
    
    @objc fileprivate func goback_topmost_controller_handle(noti:Notification){
        
        if let toController = noti.userInfo?["controller"] as? UIViewController{
           
            print("试试呢：",toController)
            
            if toController == self{
                
                self.header.continuePlay()
            }
        }
        
        
        
    }
    
    @objc fileprivate func ban_current_user_handle(){
        
        
        
        guard let m = self.headerModel else{
            return
        }
        
        BAN_SOMEBODY_HANDLE(userId: m.userInfo.accid, close_view: false, hud_controller: self)
        
    }
    
    fileprivate func deleteAlert(id:String){
        
        JVrequest(PH.deleteDailyApi,parameters: ["daily_content_id":id],success: { (json) in
            
            NotificationCenter.default.post(name: Notification.Name.DelDaily, object: nil, userInfo: ["id":id])
            
            self.goback_previous_controller()
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
        
    }
    
    override func right_click() {
        
        
        let vc = ST_BTSheetActionController.init(title: nil, message: nil)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
    //        是自己 只有删除
        if self.headerModel?.userInfo.accid == Defaults[.currentUserID]{
            
            let str2 = NSMutableAttributedString.init(string: "删除")
            
            str2.addAttributes(attr, range: NSRange(location: 0, length: str2.length))
            
            vc.addAction(ST_BTAlertAction.init(title: str2, handler: {[weak self] (action) in
                
                guard let m = self?.headerModel else{
                    return
                }
                
                PlayFeedBack()
                
                let attrString = NSMutableAttributedString(string: "确认要删除此日常吗？")
                
                let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
                attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
                
                let messageAttrString = NSMutableAttributedString(string: "删除后点赞和评论会被清空")
                
                let attr2: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.38, green: 0.4, blue: 0.44, alpha: 1)]
                
                messageAttrString.addAttributes(attr2, range: NSRange(location: 0, length: messageAttrString.length))
                
                let alert = ST_BTAlertViewController.init(title: attrString, message: messageAttrString, imageName: "首页_icon_提示", confirmText: " 确定删除", cancelText: "再想想看")
                
                alert.overCurrentContext = true
                
                alert.over_current_context_alpha = "0.4"
                
                alert.confirm_closure = {[weak self] in
                    
                    self?.deleteAlert(id: m.dailyId)
                    
                }
                
                GlobalPresent(toController: alert, animated: false)
                
                
                
            }))
            
            
            vc.show()
            
            return
            
        }
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male || Defaults[.isPanda] {
        
        let str2 = NSMutableAttributedString.init(string: "拉黑")
        
        str2.addAttributes(attr, range: NSRange(location: 0, length: str2.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str2, handler: {[weak self] (action) in
            
            self?.ban_current_user_handle()
            
        }))
        
        }
        
        let str3 = NSMutableAttributedString.init(string: "举报")
        
        str3.addAttributes(attr, range: NSRange(location: 0, length: str3.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str3, handler: { (action) in
            
            let vc = ST_ReportPersonController()
            vc.userId = self.headerModel?.userInfo.accid ?? ""
            let nav = UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
            GlobalPresent(toController: nav)
            
        }))
        
        vc.show()
        
    }
    //    MARK: - Request Data
    var userId = ""
    
    var dailyId = ""
    
    fileprivate var currentPage = 0
    
    fileprivate var data_array = [ST_CommentTableCellModel]()
    
    fileprivate var headerModel:ST_DaliyMomentDetialHeaderModel?
    
    fileprivate func request_data(){
        
        currentPage = 1
        
        JVrequest(PH.dailyDetailApi,parameters: ["daily_content_id":dailyId,"target_accid":userId], success: { (json) in
            
            let data = json["data"]
            
            print("错误222--：",data)
            
            self.headerModel = ST_DaliyMomentDetialHeaderModel.init(fromJson: data)
            
            self.headerModel?.dailyId = self.dailyId
            
            var count = 0
            
            if let list = [ST_CommentTableCellModel].deserialize(from: data["comment"]["list"].rawString() ?? "") as? [ST_CommentTableCellModel]{
                
                list.forEach{
                    $0.ownUserId = self.userId
                    $0.setUpDataSet()
                }
                
                count = list.count
                
                self.data_array = list
                
            }
            
            if let hModel = self.headerModel{
                
                self.header.model = hModel
                
                self.header.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: hModel.cellHeight)
                
                self.tableView.tableHeaderView = self.header
                
            }
            
            if count < 1{
                
                self.tableView.tableFooterView = ST_DaliyMomentDetialEmptyView.init(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ST_DaliyMomentDetialEmptyView.height))
                
            }else{
                self.tableView.tableFooterView = nil
            }
            
            
            self.tableView.mj_footer?.endRefreshing()
            self.tableView.mj_header?.endRefreshing()
            
            self.tableView.reloadData {
                
                self.load_more_option_style(tableView: self.tableView, count: count, pageSize: 30) {
                    
                    self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                        
                        self?.request_comment_data()
                    })
                }
                
                
                if self.openInputCommentBar{
                    self.openInputCommentBar = false
                    
                    main_thread_execute(afterDelay: 0.5) {
                        self.comment_input_bar.startEdit()
                    }
                    
                    
                }
                
            }
            
            self.hidden_indeterminate_h_u_d()
            
            
        }) { (code, err) in
            
            
            self.toast(text: err)
            
            self.tableView.mj_footer?.endRefreshing()
            self.tableView.mj_header?.endRefreshing()
        }
        
        
    }
    
    
    fileprivate func request_comment_data(){
        
        currentPage += 1
        
        
        JVrequest(PH.dailyCommentListApi,parameters: ["daily_content_id":dailyId,"page":currentPage], success: { (json) in
            
            let data = json["data"]
            var count = 0
            if let list = [ST_CommentTableCellModel].deserialize(from: data["list"].rawString() ?? "") as? [ST_CommentTableCellModel]{
                
                list.forEach{
                    $0.ownUserId = self.userId
                    $0.setUpDataSet()
                }
                
                count = list.count
                
                self.data_array += list
                
            }
            
            
            self.tableView.mj_footer?.endRefreshing()
            self.tableView.mj_header?.endRefreshing()
            
            self.tableView.reloadData {
                
                self.load_more_option_style(tableView: self.tableView, count: count, pageSize: 30) {
                    
                    self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                        
                        self?.request_comment_data()
                    })
                }
            }
            
            self.hidden_indeterminate_h_u_d()
            
            
        }) { (code, err) in
            
            
            self.toast(text: err)
            
            self.tableView.mj_footer?.endRefreshing()
            self.tableView.mj_header?.endRefreshing()
        }
        
    }
    
    //    MARK: - Properties
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView()
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 100 , right: 0)
        
        control.delegate = self
        control.dataSource = self
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        control.register(cellWithClass: UITableViewCell.self)
        control.register(cellWithClass: ST_CommentTableCell.self)
        
        control.separatorStyle = .none
        
        control.backgroundColor = Color.white
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        
        return control
    }()
    
    fileprivate lazy var header:ST_DaliyMomentDetialHeaderView = {
       let control =  ST_DaliyMomentDetialHeaderView()
        control.comment_click_closure = {[weak self] in
            
            self?.comment_input_bar.startEdit()
        }
        return control
    }()
    
    fileprivate lazy var bottom_input_action_view:ST_PecGroupBottomView = {
        let control = ST_PecGroupBottomView()
        control.beginInput = {[weak self] in
            self?.comment_input_bar.startEdit()
        }
        return control
    }()
    
    
    fileprivate lazy var comment_input_bar:ST_CommentInputBar = {
        let control = ST_CommentInputBar()
        control.endEditClosure = {[weak self] str,replyId,commentId in
            
            self?.end_edit_comment_handle()
            
            self?.send_message_handle(comment: str, replyUserId: replyId, commentId: commentId)
        }
        control.keyBroadHiddenClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: true)
        }
        control.keyBroadShowClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: false)
        }
        return control
    }()
    
    fileprivate lazy var comment_input_mask_view:UIView = {
        let control = UIView()
        control.alpha = 0
        control.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(end_edit_comment_handle))
        control.addGestureRecognizer(tap)
        return control
    }()
    
    fileprivate var first = true
}

//MARK: - Event
extension ST_DaliyMomentDetailController{
    
    @objc fileprivate func end_edit_comment_handle(){
        
        comment_input_bar.endEditing(true)
        
        
    }
    
    func hidden_mask_view(hidden:Bool){
        
        UIView.animate(withDuration: 0.25, animations: {
            
            self.comment_input_mask_view.alpha = hidden ? 0 : 1
            
        }) { (f) in
            
        }
        
    }
    
    func send_message_handle(comment:String,replyUserId:String?,commentId:String?){
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        
        
        var param = ["target_accid":self.userId,"daily_content_id":self.dailyId,"comment":comment] as [String : Any]
        
        if let id = commentId{
            param.updateValue(id, forKey: "target_comment_id")
        }
        if let id = replyUserId{
            param.updateValue(id, forKey: "target_member_id")
            
            if let headerData = self.headerModel{
                
                ST_BTGlobalDataCenter.shared.replyDailyCommentEvent(daily_id: headerData.dailyContent.dailyId, reply_user_id: id, dailyType: headerData.dailyContent.name, source: "个人日常页", isMyDaily: self.userId == Defaults[.currentUserID])
                
            }
        }
        
        if let headerData = self.headerModel{
            
            
            ST_BTGlobalDataCenter.shared.commentDailyEvent(dailyType: headerData.dailyContent.name, daily_id: headerData.dailyContent.dailyId, commented_user_id: self.userId)
            
        }
        
        
        JVrequest(PH.commentDailyApi,parameters: param, success: { (json) in
            
            self.currentPage = 0
            
            self.request_data()
            
        }) { (code, err) in
            self.toast(text: err)
        }
        
        
    }
    
    
}
//MARK: - UITableViewDelegate
extension ST_DaliyMomentDetailController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withClass: ST_CommentTableCell.self, for: indexPath)
        
        cell.model = data_array[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return data_array[indexPath.row].cellHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let m = data_array[indexPath.row]
        
        let nickname = m.nickname
        
        self.comment_input_bar.startEdit(replyUserId: m.id.string, commentId: m.comment_id.string, nickName: nickname)
        
    }
    
    
}

